<template>
  <div class="main-app">
    <el-card class="box-card">
      <el-form :inline="true" :model="formInline" class="form-inline">
        <el-form-item label="转移计划编号:">
          <el-input v-model="formInline.number" clearable />
        </el-form-item>
        <el-form-item label="产废单位名称:">
          <el-input v-model="formInline.orgName" clearable />
        </el-form-item>
        <!--        <el-form-item label="年份:">
          <el-input v-model="formInline.waste" clearable />
        </el-form-item> -->

        <el-form-item label="状态:">
          <el-select v-model="formInline.type" placeholder="请选择" clearable>
            <el-option v-for="item in transportPlanStateOption" :key="item.value" :label="item.label"
                       :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh-right" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="show-result">

      <!-- 加载动态菜单 -->
      <el-form :inline="true" class="form-inline">
        <el-form-item v-for="item in toolbtn" :key="item.id">
          <el-button type="primary" :icon="item.meta.icon" @click="showViews(item.name)">
            {{ item.meta.title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <div> 当前页统计：废物总重量：
            {{ summaryWastWeight }} 吨
          </div>
        </el-form-item>
      </el-form>

      <!-- <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" icon="el-icon-folder-checked" :disabled="disabled" @click="approval('20')">
            审批通过
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-folder-delete" :disabled="disabled" @click="approval('30')">
            拒绝审批
          </el-button>
        </el-form-item>
        来宾市不需要此功能
        <el-form-item>
          <el-button type="primary" icon="el-icon-folder-delete" :disabled="disabled" @click="approval('15')">
            审核通过并转交监管端审核
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-view" :disabled="disabled" @click="view">
            查看计划
          </el-button>
        </el-form-item>
      </el-form> -->

      <div class="result" style="margin-top: -40px;">
        <div class="tool">
          <el-button type="primary" size="mini" icon="el-icon-notebook-1" :disabled="deleteDisabled" plain
                     @click="exportData"
          />
          <el-button type="primary" size="mini" icon="el-icon-printer" plain @click="printData" />
        </div>
        <el-table id="table" ref="multipleTable" v-loading="loading" border :data="tableData" tooltip-effect="dark"
                  style="width: 100%" @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="number" label="转运计划编号" />
          <el-table-column prop="wpcName" label="产废单位名称" />
          <el-table-column prop="totalWeightOfWaste" label="拟转移废物总重量（吨）" />
          <!-- <el-table-column prop="type" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">{{ scope.row.type | parseType }}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="type" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.typeColor">{{ scope.row.typeName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startProposedTransferTime" label="起始日期">
            <template slot-scope="scope">
              {{ scope.row.startProposedTransferTime | parseDateB }}
            </template>
          </el-table-column>
          <el-table-column prop="endProposedTransferTime" label="截止日期">
            <template slot-scope="scope">
              {{ scope.row.endProposedTransferTime | parseDateB }}
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="申请人" />
          <el-table-column prop="createTime" label="申请时间">
            <template slot-scope="scope">
              {{ scope.row.createTime | parseDate }}
            </template>
          </el-table-column>

        </el-table>
        <div class="page">
          <el-pagination background :current-page.sync="currentPage" layout="total,prev, pager, next,sizes"
                         :total="total" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" @current-change="handleCurrentChange"
                         @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// Table组件相关逻辑，需要引用
import {
  pageMixin
} from "../../../mixins/index";
import {
  transportPlanState
} from "../../../utils/resource.js";
import {
  getFloat
} from '../../../utils/index.js';
import {
  getTransportPlanList,
  approval
} from '../../../api/wastereceipt.js';

export default {
  filters: {
    parseDate(value) {
      if (value) {
        return value.replace("T", " ");
      }
    },
    parseDateB(value) {
      if (value) {
        return value.substr(0, 10).replace("T", " ");
      }
    },
    parseType(value) {
      if (value != null) {
        return transportPlanState.find((p) => p.value === `${value}`).label;
      }
    },

  },
  mixins: [pageMixin],
  data() {
    return {
      transportPlanStateOption: transportPlanState,
      formInline: {
        number: "",
        orgName: "",
        type: ""
      },
      toolbtn: [] // 列表顶部按钮
    };
  },
  async created() {
    this.transportPlanStateOption = transportPlanState.filter(item => item.value === "10" || item.value === "20" ||
        item.value === "30");
    await this.init();
  },
  methods: {
    // 列表顶部功能按钮点击事件
    showViews(action) {
      // console.log(action);
      switch (action) {
        case '审批通过':
          this.approval('20');
          break;
        case '拒绝审批':
          this.approval('30');
          break;
        case '审核通过并转交监管端审核':
          this.approval('15');
          break;
        case '查看计划':
          if (this.ids.length !== 1) {
            this.$message.error('此功能仅限操作1条数据！');
            return;
          }
          this.view();
          break;
      }
    },
    async init() {
      this.tableData = [];
      this.loading = true;
      var searchType = "10,20,30";
      if (this.formInline.type) {
        searchType = this.formInline.type;
      }
      const {
        data,
        count
      } = await getTransportPlanList({
        limit: this.pageSize,
        page: this.currentPage,
        searchParam: JSON.stringify({
          Number: this.formInline.number,
          OrgName: this.formInline.orgName,
          Type: searchType,
          Time: "",
		  AreaNumber:  this.$store.state.user.userObj.areaNumberStr,
        })
      });
      this.tableData = data;
      this.undataSummaryData(data);
      this.tableData.forEach(item => {
        var obj = transportPlanState.find((p) => p.value === `${item.type}`);
        if (obj) {
          item.typeName = obj.label;
          item.typeColor = obj.color;
        } else {
          item.typeName = "无数据";
          item.typeColor = "red";
        }
      });
      this.total = count;
      this.loading = false;

      // 初始化按钮数据
      this.toolbtn = JSON.parse(localStorage.getItem('转运计划备案'));
      // console.log(this.toolbtn);
    },

    // 20: 审核已通过  30: 审核未通过
    async approval(value) {
      const arr = this.$refs.multipleTable.selection;
      if (arr.length !== 1) {
        this.$message.error('此功能仅限操作1条数据！');
        return;
      }
      if (arr[0].type !== "10") {
        console.log(arr[0]);
        this.$message.error('所选信息已经审核完毕，请选择待审核数据进行操作  ');
        return;
      }

      let confimText = "";
      if (value === "20") {
        confimText = "审核通过";
      } else if (value === "30") {
        confimText = "拒绝审核";
      } else {
        confimText = "审核通过并转交监管端审核";
      }
      this.$confirm(`此操作将所选转运计划信息状态设置为：${confimText}状态, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async() => {
        let ids2 = '';
        for (let i = 0; i < arr.length; i++) {
          if (i === 0) {
            ids2 += arr[i].id
          } else {
            ids2 += ("," + arr[i].id)
          }
        }
        var formdata = {
          Id: ids2,
          Type: value
        };
          // 操作数据
        await approval(formdata);
        await this.init();
        this.$message({
          type: "success",
          message: `${confimText}状态更新成功!`,
        });
      });
    },
    undataSummaryData(tableDataList) {
      this.summaryWastWeight = 0;

      tableDataList.forEach(item => {
        if (item.totalWeightOfWaste < 0) {
          item.totalWeightOfWaste = 0
        }
        this.summaryWastWeight += item.totalWeightOfWaste;
      })
      this.summaryWastWeight = getFloat(this.summaryWastWeight, 5)
    },
    view() {
      this.$router.push(`/wastereceipt/planfiling/detail/${this.id}`);
    },
    edit() {
      var obj = this.tableData.find((p) => p.id === this.id);

      if (obj) {
        if (obj.type !== "0") {
          this.$message({
            message: '当前转运计划已提交，不能修改',
            type: 'warning'
          });
          return
        } else {
          localStorage.removeItem('tempTransportPlanFormInfo');
          this.$router.push(`/wastereceipt/planfiling/edit/${this.id}`);
        }
      } else {
        this.$message.error('信息无效');
      }
    },
    add() {
      this.$router.push("/wastereceipt/planfiling/create");
    },
    async reset() {
      this.formInline = {
        number: "",
        orgName: "",
        type: ""

      };
      await this.init();
    },
  },
};
</script>

<style lang="scss" scoped>
  .result {
    margin-top: 10px;
  }

  .page {
    margin-top: 20px;
    text-align: right;
    margin-bottom: 40px;
  }

  .show-result {
    margin-top: 10px;
  }
</style>
